<?php

class Crud_Navigation extends Zend_Navigation
{
	protected $_module = 'admin';
	protected $_controller = 'crud';
	
	public $mainPage;
	
	/**
	* @var Zend_Acl_Role
	*/
	protected $role;	

	public function setRole($role) 
	{
		$this->role = $role;
	}

	public function getRole()
	{
		return $this->role;
	}
    /**
     * Creates a new crud navigation container
     *
     * @return void
     * @throws Zend_Navigation_Exception  if $pages is invalid
     */
    public function init()
    {    	
    	$acl = Crud_Acl::getInstance();
    	
		$mainPage = new Zend_Navigation_Page_Mvc();
		$mainPage->setModule($this->_module);
		$mainPage->setController($this->_controller);
		$mainPage->setAction('index');

		$mainPage->setLabel('Главное меню');
		$this->addPage($mainPage);

		$peer = AdminSectionPeer::getInstance();
		$select = $peer->select();
		$select->order('order asc');
    	$rowset = $peer->fetchAll($select);

    	$resources = $acl->getResources();
		foreach ($rowset as $row) {
			$aclResource = $row->getKey();
			if (!in_array($row->getKey(), $resources)) {
				$aclResource = 'dummy';
			}
			
			$parentPage = $mainPage;
			
			$groupRow = $row->getAdminSectionGroupRowByGroupId();
			if ($groupRow) {
				
				$page = isset($groups[$groupRow->getKey()]) ? $groups[$groupRow->getKey()] : null;
				if (!$page) {
					$page = new Zend_Navigation_Page_Mvc();
					$page->setModule($this->_module);
					$page->setController($this->_controller);
					$page->setAction('index');
					$page->setParams(array('group' => $groupRow->getId()));
					$page->setLabel($groupRow->getName());
					$page->setClass('collapsible');
					
					$groups[$groupRow->getKey()] = $page;
					$mainPage->addPage($page);
				}
				
				$parentPage = $groups[$groupRow->getKey()];
			}
			
			
/*			if (!$acl->isAllowed($this->getRole(), 
$aclResource, 'read')) {
				continue;
			}*/
			$page = new Zend_Navigation_Page_Mvc();
			$page->setModule($this->_module);
			$page->setController($this->_controller);
			$page->setAction('list');
			$page->setParams(array('table' => $row->getKey()));
			$page->setPrivilege('read');
			$page->setResource($aclResource);

			$pageAdd = clone $page;
			$pageAdd->setAction('add');
			$pageAdd->setLabel('Добавление');
			$pageAdd->setPrivilege('create');

			$pageEdit = clone $page;
			$pageEdit->setVisible(false);
			$pageEdit->setAction('edit');
			$pageEdit->setLabel('Редактирование');
			$pageAdd->setPrivilege('update');

			$page->addPages(array($pageAdd, $pageEdit));

			$page->setLabel($row->getName());
			$parentPage->addPage($page);
		}
		$container = $mainPage;
		//$this->view->container = $container;
		//d($container);
		$this->mainPage = $mainPage;
    }    
}
